<?php

namespace App\Http\Middleware;

use Closure;
use Countable;
use Illuminate\Support\Facades\Log;

class AccessMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $begin = microtime(true);
        $response = $next($request);

        $end = microtime(true);
        // clientip、uri、cost、request、respone
        $clientip = $request->getClientIp();
        $uri = $request->getMethod() . ' ' . $request->getUriForPath($request->getPathInfo());
        $cost = $end - $begin;
        $req = $request->all();

        $logData = compact('cost', 'clientip', 'uri', 'req');
        $logMsg = '';
        foreach ($logData as $key => $value) {
            $logMsg .= '[' . $key . ': ' . json_encode($value) . '] ';
        }
        Log::channel('access')->info(stripslashes($logMsg));
        return $response;
    }
}
